<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreVillageRequest;
use App\Http\Requests\UpdateVillageRequest;
use App\Models\Village;
use App\Models\Wxuser;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class VillageController extends Controller
{
    public function index(Request $request)
    {
        $name = $request->name;

        $villages = Village::when($name, function ($query) use ($name) {
            $query->where('name', 'like', '%'.$name."%");
        })->paginate(10);
        return $villages;
    }


    public function store(StoreVillageRequest $request)
    {
        $request->validate([
            'vid' => ['required', Rule::unique('villages', 'vid')],
            'name' => ['required', Rule::unique('villages', 'name')],
        ]);
        Village::create($request->input());
        return $this->message("添加成功");
    }

    public function update(UpdateVillageRequest $request, Village $village)
    {
        $request->validate([
            'name' => ['required', Rule::unique('villages')->ignore(request()->village)],
            'vid' => ['required', Rule::unique('villages')->ignore(request()->village)],
        ]);
        $village->update($request->input());
        return $this->message('修改成功');
    }

    public function destroy(Village $village)
    {
        $village->delete();
        return $this->message("删除成功");
    }

    //为行政村设置干部
    public function setAdmin(Request $request, Village $village, Wxuser $wxuser)
    {
        $village->wxusers()->syncWithoutDetaching([$wxuser->id]);
        return $this->message("设置成功");
    }

    //将当前用户  取消XX村  管理员
    public function cancelAdmin(Request $request, Village $village, Wxuser $wxuser)
    {
        $village->wxusers()->detach($wxuser->id);
        return $this->message("取消成功");
    }
}
